package com.hj.springframework3.proxy;

import com.hj.springframework3.annotation.Component;
import com.hj.springframework3.annotation.Order;
import com.hj.springframework3.context.BeanPostProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author : hujing
 * @Date: 2025/7/7 10:24
 * @Description:
 */
@Component
@Order(200)
public class SecondBeanPostProcessor implements BeanPostProcessor {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    Map<String,Object> originBeans = new HashMap<>();

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        if (OriginBean.class.isAssignableFrom(bean.getClass())){
            logger.info("为"+beanName+"创建第二个代理对象");
            SecondProxyBean proxy = new SecondProxyBean((OriginBean) bean);
            originBeans.put(beanName,bean);
            return proxy;
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }

    /**
     * 根据名字获取原始bean
     * @param bean
     * @param beanName
     * @return
     */
    @Override
    public Object postProcessOnSetProperty(Object bean, String beanName) {
        Object origin = originBeans.get(beanName);
        if (origin != null){
            logger.debug("auto set property for {} from second proxy {} to origin bean: {}", beanName, bean, origin);
            return origin;
        }
        return bean;
    }
}
